<template>
  <div class="app-container">
    <el-button type="primary" plain @click="add">新增</el-button>
    <div style="padding: 10px" />

    <el-table
      v-loading="listLoading"
      :data="tableData"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="党员姓名" align="center" prop="userName" />
      <el-table-column label="党组织机构" align="center" prop="djDeptName" />
      <el-table-column label="党组织角色" align="center" prop="djRoleName" />
      <el-table-column label="入党时间" align="center" prop="admissionTime" />
      <el-table-column label="党龄" align="center" prop="partyAge" width="120" />
      <el-table-column label="出生日期" align="center" prop="birthTime" />
      <el-table-column label="年龄" align="center" prop="age" width="120" />
      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            plain
            @click="edit(scope.row.djUserId)"
          >
            编辑
          </el-button>
          <el-button size="mini" type="danger" plain @click="remove(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding: 10px" />
    <el-pagination
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
      :current-page="pageNum"
      :page-size="pageSize"
      :total="total"
      @size-change="onPageSizeChange"
      @current-change="onCurrentPageChange"
    />

    <el-dialog
      width="700px"
      :title="title"
      :visible.sync="visible"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="7em">
        <el-row>
          <el-col :span="12">
            <el-form-item label="原部门名称" prop="deptId">
              <el-select
                style="width: 100%"
                v-model="form.deptId"
                :disabled="title === '编辑'"
                placeholder="请选择原部门"
                @change="changeDept"
              >
                <el-option
                  v-for="item in deptList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="党员姓名" prop="djUserId">
              <el-input
                v-if="title === '编辑'"
                v-model="form.userName"
                disabled
              />
              <el-select
                style="width: 100%"
                v-else
                v-model="form.djUserId"
                placeholder="请选择党员"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入党时间" prop="admissionTime">
              <el-date-picker
                style="width: 100%"
                v-model="form.admissionTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择入党时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="党组织机构" prop="djDeptId">
              <el-cascader
                style="width: 100%"
                v-model="form.djDeptId"
                :options="zuzhiList"
                :props="treeProps"
                placeholder="选择党组织机构"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="党组织角色" prop="djRoleId">
              <el-select
                style="width: 100%"
                v-model="form.djRoleId"
                multiple
                placeholder="请选择党组织角色"
              >
                <el-option
                  v-for="item in roleList"
                  :key="item.djRoleId"
                  :value="item.djRoleId"
                  :label="item.djRoleName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthTime">
              <el-date-picker
                style="width: 100%"
                v-model="form.birthTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择出生日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item class="dialog-footer">
          <el-button @click="visible = false">关 闭</el-button>
          <el-button type="primary" @click="submit">提 交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  getZuzhiList,
  getRoleOption,
  getDeptOption,
  getUserOption,
  getUserPage,
  getUserDetail,
  addUser,
  editUser,
  deleteUser,
} from "@/api2/partyManage";
import { handleTree } from "@/utils/utils";

export default {
  data() {
    return {
      tableData: [],
      listLoading: true,
      pageNum: 1,
      pageSize: 10,
      total: 0,
      visible: false,
      title: "",
      treeProps: {
        value: "djDeptId", // ID字段名
        label: "djDeptName", // 显示名称
        children: "children", // 子级字段名
      },
      form: {
        djRoleId: [],
      },
      rules: {
        deptId: [
          { required: true, message: "原部门名称不能为空", trigger: "change" },
        ],
        djUserId: [
          { required: true, message: "党员姓名不能为空", trigger: "change" },
        ],
        admissionTime: [
          { required: true, message: "入党时间不能为空", trigger: "change" },
        ],
        djDeptId: [
          {
            required: true,
            message: "党组织机构不能为空",
            trigger: ["blur", "change"],
          },
        ],
        djRoleId: [
          { required: true, message: "党组织角色不能为空", trigger: "change" },
        ],
        birthTime: [
          { required: true, message: "出生日期不能为空", trigger: "change" },
        ],
      },
      roleList: [],
      zuzhiList: [],
      deptList: [],
      userList: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      getUserPage({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      }).then((data) => {
        this.listLoading = false;
        this.tableData = data.data;
        this.total = data.total;
      });
    },
    onPageSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.getList();
    },
    onCurrentPageChange(val) {
      this.pageNum = val;
      this.getList();
    },
    async getRoleData() {
      const res = await getRoleOption();
      this.roleList = res.data;
    },
    async getTreeData() {
      const res = await getZuzhiList();
      this.zuzhiList = handleTree(res.data, "djDeptId");
    },
    async getDepttData() {
      const res = await getDeptOption();
      this.deptList = res.data;
    },
    async changeDept(val) {
      this.$delete(this.form, "djUserId");
      const res = await getUserOption({ departmentId: val });
      this.userList = res.data;
    },
    getOption() {
      Promise.all([
        this.getTreeData(),
        this.getRoleData(),
        this.getDepttData(),
      ]);
    },
    add() {
      this.title = "新增";
      this.visible = true;
      this.resetForm();
      this.form = {
        djRoleId: [],
      };
      this.getOption();
    },
    async edit(id) {
      this.title = "编辑";
      this.visible = true;
      await this.getOption();
      const res = await getUserDetail({ djUserId: id });
      const { data } = res;
      let parentIds = data.ancestors?.split(",").map(Number);
      parentIds.shift();
      data.djDeptId = [...parentIds, data.djDeptId];
      data.djRoleId = data.djRoleId?.split(",").map(Number);
      this.form = data;
    },
    submit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let { djDeptId, djRoleId, ...form } = this.form;
          djDeptId = djDeptId[djDeptId.length - 1];
          djRoleId = this.form.djRoleId.join();
          const params = { djDeptId, djRoleId, ...form };
          if (this.title === "编辑") {
            await editUser(params);
            this.$message.success("修改成功");
          } else {
            await addUser(params);
            this.$message.success("新增成功");
          }
          this.visible = false;
          this.getList();
        }
      });
    },
    resetForm() {
      if (!this.$refs.form) return;
      this.$refs.form.resetFields();
    },
    remove(row) {
      this.$confirm("是否删除名称为 " + row.userName + " 的数据项?", {
        type: "warning",
      })
        .then(async () => {
          await deleteUser(row.djUserId);
          this.$message.success("删除成功");
          this.getList();
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog-footer {
  margin-bottom: 0;
  text-align: center;
  ::v-deep {
    .el-form-item__content {
      margin-left: 0 !important;
    }
  }
}
#tree-option .el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  padding: 0;
  background-color: #fff;
  height: auto;
}

::v-deep {
  .el-tree-node.is-current > div:first-child,
  .el-tree-node__content:focus {
    background-color: #ecf5ff;
    color: #409eff;
  }
}
</style>
